package com.le.tester.javaThink.fourth.concurrency;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * createTime：2022/1/27 16:21
 * description：SimpleMicroBenchmark
 */

abstract class IncrementTable {
    protected long counter = 0;

    public abstract void increment();


}

class SynchronizingTest extends IncrementTable {
    public synchronized void increment() {
        ++counter;
    }
}

class LockingTest extends IncrementTable {
    private Lock lock = new ReentrantLock();

    @Override
    public void increment() {
        lock.lock();
        try {
            ++counter;
        } finally {
            lock.unlock();
        }
    }
}

public class SimpleMicroBenchmark {
    static long test(IncrementTable incr) {
        long start = System.nanoTime();
        for (int i = 0; i < 1000000L; i++) {
            incr.increment();
        }
        return System.nanoTime() - start;
    }

    public static void main(String[] args) {
        long synchTime = test(new SynchronizingTest());
        long lockTime = test(new LockingTest());
        System.out.println("synchTime:" + synchTime);
        System.out.println("lockTime:" + lockTime);
    }

}
